from collections import OrderedDict
from goods.models import GoodsChannel

def get_categories():
    # 准备商品分类得字典
    categories = OrderedDict()
    # 查询并展示商品分类
    # channels = GoodsChannel.objects.all()
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 遍历所有的频道
    for channel in channels:
        # 获取当前频道得组
        group_id = channel.group_id
        # 构造基本的数据框架
        categories[group_id] = {'channels': [], 'sub_cats': []}
        cata1 = channel.category
        # 将cat1添加到channels中
        categories[group_id]['channels'].append({
            'id': cata1.id,
            'name': cata1.name,
            'url': channel.url,
        })
        # 遍历二级类别
        for cat2 in cata1.subs.all():
            cat2.sub_cats = []
            ss = []
            for cat3 in cat2.subs.all():
                # ss.append(cat3.name)
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)
    return categories